package com.whut.f2f.chat;

import com.whut.f2f.chat.connector.Connector;
import com.whut.f2f.chat.message.MessageProcessor;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ChatServer消息接收处理
 *
 * Created by null on 2017/1/20.
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger log = LoggerFactory.getLogger(ChatServerHandler.class);

    private Connector connector;
    private final MessageProcessor messageProcessor = new MessageProcessor();

    public void setConnector(Connector connector) {
        this.connector = connector;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.debug("client connect: {}", ctx.channel().id());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.debug("receive from client: {}", msg);
        messageProcessor.process(msg, ctx.channel(), connector);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.debug("client disConnect: {}", ctx.channel().id());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
